import { Component, Host, ViewChild, ElementRef, ChangeDetectionStrategy, ChangeDetectorRef, OnInit, AfterViewInit } from '@angular/core';
import { AppComponent } from '../../app.component';
import { HomeService } from './home.service';
import { KnowledgeCenterService } from '../knowledge-center/knowledge-center.service';
import { MostActiveReportModel } from './models/mostActiveReport.model';
import { InsightModel } from '../knowledge-center/models/insight.model';
import { MostRecentActivityModel } from './models/mostRecentActivity.model';
import { NewsBaseModel } from '../knowledge-center/models/news.model';
import { PortfolioBaseModel } from './models/portfolio.model';
import { EventModel } from '../knowledge-center/models/event.model';
import { StorageService } from '../../shared/services/storage.service';
import { Profile } from '../../framework/login/models/profile.model';
import { BaseComponent } from '../../shared/components/baseComponent/base.component';
import { SearchType } from '../../shared/components/search/search.service';

import * as $ from 'jquery';
import { NotificationsStatus } from './models/notifications.model';
import * as truncate from 'html-truncate';
import { AnalyticsService } from '../../shared/services/googleAnalytics.service';
import { GoogleAnalyticsBeacon } from '../../shared/models/googleAnalytics.model';


/**
 * Home main component
 *
 * Author: Sorin Spiru, Andrei Istrate
 * Date: 13.01.2018
 */
@Component({
    moduleId: module.id,
    templateUrl: 'home.component.html',
    styleUrls: ['./home.component.scss'],
    providers: [HomeService, KnowledgeCenterService],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class HomeComponent extends BaseComponent implements OnInit, AfterViewInit {

    @ViewChild('videoTutorial') videoTutorial: ElementRef
    public searchType: SearchType = SearchType.company;
    public portfolios: PortfolioBaseModel[] = [];
    public spotlights: NewsBaseModel[] = [];
    public recentActivity: MostRecentActivityModel[] = [];
    public events: EventModel[] = [];
    public top20reports: MostActiveReportModel[] = [];
    public insights: InsightModel[] = [];
    public hasNotification: boolean = false;
    public notificationBody: string;
    public notificationCharLimit = 165;
    public user: Profile = StorageService.get().userInfo;
    public numCompanies = 11000;
    public showFullNotification = false;
    public selectedInsight: InsightModel;
    public selectedEvent: EventModel;

    constructor(
        private homeService: HomeService,
        private kcService: KnowledgeCenterService,
        private analyticsService: AnalyticsService,
        private cdRef: ChangeDetectorRef,
        @Host() private rootComponent: AppComponent) {
        super(cdRef);
    }

    ngOnInit() {
        this.homeService.getPortfolios().subscribe(data => {
            this.portfolios = data.portfolios.filter((item, index) => index < 3);
            this.cdRef.markForCheck();
        }, error => {
            this.portfolios = undefined;
            this.cdRef.markForCheck();
            throw error;
        });

        this.kcService.getSpotlight(true).subscribe(data => {
            this.spotlights = data;
            this.cdRef.markForCheck();
        }, error => {
            this.spotlights = undefined;
            this.cdRef.markForCheck();
            throw error;
        });

        this.homeService.getMostRecentActivity().subscribe(data => {
            this.recentActivity = data;
            this.cdRef.markForCheck();
        }, error => {
            this.recentActivity = undefined;
            this.cdRef.markForCheck();
            throw error;
        });

        this.kcService.getEvents(true).subscribe(data => {
            this.events = data.items;
            this.cdRef.markForCheck();
        }, error => {
            this.events = undefined;
            this.cdRef.markForCheck();
            throw error;
        });

     /*    this.homeService.getTop20ActiveReports().subscribe(data => {
            this.top20reports = data;
            this.cdRef.markForCheck();
        }, error => {
            this.top20reports = undefined;
            this.cdRef.markForCheck();
            throw error;
        }); */

        this.kcService.getKnowledge(true).subscribe(data => {
            this.insights = data;
            this.cdRef.markForCheck();
        }, error => {
            this.insights = undefined;
            this.cdRef.markForCheck();
            throw error;
        });

        this.homeService.getNotification().subscribe(data => {
            this.hasNotification = data.status == NotificationsStatus.Published;
            this.notificationBody = data.body;
            this.cdRef.markForCheck();
        }, error => {
            this.hasNotification = false;
            this.notificationBody = undefined;
            this.cdRef.markForCheck();
            throw error;
        });

        this.rootComponent.finishLoading();
    }

    ngAfterViewInit() {
        $('.carousel .carousel-item').each(function() {
            let next = $(this).next();
            if (!next.length) {
                next = $(this).siblings(':first');
            }
            next.children(':first-child').clone().appendTo($(this));

            for (let i = 0; i < 2; i++) {
                next = next.next();
                if (!next.length) {
                    next = $(this).siblings(':first');
                }

                next.children(':first-child').clone().appendTo($(this));
            }
        });
    }

    public play(video: any): void {
        video.play();
    }

    public stop(video: any): void {
        video.pause();
        video.currentTime = 0;
    }

    get greeting(): string {
        const hour = new Date().getHours();
        const timeOfDay = hour < 12 ? 'Morning' : (hour < 18 ? 'Afternoon' : 'Evening');
        return `Good ${timeOfDay}, ${this.user.firstName}`;
    }

    public loadInsight( insightId ): void {
        this.analyticsService.sendBeacon(new GoogleAnalyticsBeacon('News', 'Home', { InsightId: insightId }));
        this.kcService.getKnowledgeById(insightId)
            .subscribe(insight => {
                this.selectedInsight = insight;
                this.cdRef.markForCheck();
            });
    }

    public loadEvent( eventId ): void {
        this.analyticsService.sendBeacon(new GoogleAnalyticsBeacon('Events', 'Home', { EventId: eventId }));
        this.kcService.getEventById(eventId)
            .subscribe(event => {                
                this.selectedEvent = event;
                this.cdRef.markForCheck();
            });
    }

    get notificationDisplay(): string {
        if (this.notificationBody) {
            return this.notificationBody.length <= this.notificationCharLimit || this.showFullNotification
                ? this.notificationBody
                : truncate(this.notificationBody, this.notificationCharLimit);
        }

        return '';
    }
}
